package com.mesystem.util;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;

import org.apache.log4j.LogManager;
import org.apache.log4j.PropertyConfigurator;
import org.apache.log4j.xml.DOMConfigurator;

public class Log4jInit extends HttpServlet {
	
	private static final long serialVersionUID = -427211547550002267L;

	public void init(ServletConfig config) throws ServletException {
		super.init(config);
		System.out.println("Inicia Log4jInit...");
		String log4jLocation = config.getInitParameter("log4jLocation");
		boolean log4jExternal = Boolean.getBoolean(config.getInitParameter("log4jExternal"));
		
		System.out.println("log4jLocation: " + log4jLocation);
		if(log4jExternal){
			if (log4jLocation.trim().endsWith("xml")) {
				DOMConfigurator.configure(log4jLocation);
				return;
			}
			if (log4jLocation.trim().endsWith("properties")) {
				PropertyConfigurator.configure(log4jLocation);
				return;
			}
		}else{
			
			try {
				InputStream is = Log4jInit.class.getResourceAsStream(log4jLocation);
				Properties props = new Properties();
				props.load(is);
			if (log4jLocation.trim().endsWith("xml")) {
				DOMConfigurator domConfigurator = new DOMConfigurator();
				domConfigurator.doConfigure(is, LogManager.getLoggerRepository());
				is.close();
				return;
			}
			if (log4jLocation.trim().endsWith("properties")) {
				PropertyConfigurator.configure(props);
				is.close();
				return;
			}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		throw new ServletException("Extension de archivo no reconocida");
	}
}